﻿namespace Microsoft.Extensions;

/// <summary>
/// 对象映射扩展，可考虑automapper代替
/// </summary>
public static class SimpleMapperExtensions
{
    /// <summary>
    /// 浅映射，不匹配的属性将被忽略
    /// </summary>
    /// <typeparam name="TTarget"></typeparam>
    /// <param name="source"></param>
    /// <returns></returns>
    public static TTarget SimpleMapTo<TTarget>(this object source)
    {
        Type sourceType = source.GetType();
        Type targetType = typeof(TTarget);
        TTarget target = (TTarget)Activator.CreateInstance(targetType);

        foreach (var targetProp in targetType.GetProperties())
        {
            try
            {
                var val = sourceType.GetProperty(targetProp.Name)?.GetValue(source);
                if (val != null)
                {
                    targetProp.SetValue(target, val);
                }
            }
            catch { }
        }

        return target;
    }

    /// <summary>
    /// 浅映射，不匹配的属性将被忽略
    /// </summary>
    /// <typeparam name="TTarget"></typeparam>
    /// <param name="source"></param>
    /// <param name="target"></param>
    /// <returns></returns>
    public static TTarget SimpleMapTo<TTarget>(this object source, TTarget target)
    {
        Type sourceType = source.GetType();
        Type targetType = typeof(TTarget);

        foreach (var targetProp in targetType.GetProperties())
        {
            try
            {
                var val = sourceType.GetProperty(targetProp.Name)?.GetValue(source);
                if (val != null)
                {
                    targetProp.SetValue(target, val);
                }
            }
            catch { }
        }

        return target;
    }
}
